<template>
  <div>
    <!-- 面包屑导航 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>权限管理</el-breadcrumb-item>
      <el-breadcrumb-item>角色列表</el-breadcrumb-item>
    </el-breadcrumb>

    <!-- 卡片视图 -->
    <el-card>
      <el-row>
        <el-button type="primary">添加角色</el-button>
      </el-row>
      <!-- 表格 -->
      <el-table :data="roleList" border stripe>
        <!-- 扩展栏 -->
        <el-table-column type="expand">
          <template slot-scope="scope">
            <!-- 行 -->
            <el-row
              v-for="(item1, i1) in scope.row.children"
              :key="item1.id"
              :class="[i1 === 0 ? 'border-top': '', 'border-bot', 'vcenter']"
            >
              <!-- 第一列 -->
              <el-col :span="6">
                <el-tag
                  closable
                  type="primary"
                  @close="removeRightById(scope.row,item1.id)"
                >{{item1.authName}}</el-tag>
              </el-col>
              <!-- 第二列 -->
              <el-col :span="18">
                <el-row
                  v-for="(item2, i2) in item1.children"
                  :key="item2.id"
                  :class="[i2 !== 0 ? 'border-top': '','vcenter']"
                >
                  <el-col :span="8">
                    <el-tag
                      closable
                      type="success"
                      @close="removeRightById(scope.row,item2.id)"
                    >{{item2.authName}}</el-tag>
                  </el-col>
                  <el-col :span="16">
                    <el-tag
                      closable
                      type="warning"
                      v-for="item3 in item2.children"
                      :key="item3.id"
                      @close="removeRightById(scope.row,item3.id)"
                    >{{item3.authName}}</el-tag>
                  </el-col>
                </el-row>
              </el-col>
            </el-row>
          </template>
        </el-table-column>
        <el-table-column type="index" label="#"></el-table-column>
        <el-table-column prop="roleName" label="角色名称"></el-table-column>
        <el-table-column prop="roleDesc" label="角色描述"></el-table-column>
        <el-table-column label="操作">
          <template slot-scope="scope">
            <el-button type="primary" icon="el-icon-edit" size="mini">编辑</el-button>
            <el-button type="danger" icon="el-icon-delete" size="mini">删除</el-button>
            <el-button
              type="warning"
              icon="el-icon-setting"
              size="mini"
              @click="showRightDialog(scope.row)"
            >分配角色</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 分配角色对话框 -->
    <el-dialog
      title="分配角色"
      :visible.sync="rightDialogVisible"
      width="50%"
      @close="setRightDialogClosed"
    >
      <el-tree
        :data="rightsList"
        :props="defaultProps"
        show-checkbox
        default-expand-all
        node-key="id"
        :default-checked-keys="defKeys"
        ref="treeRef"
      ></el-tree>
      <span slot="footer" class="dialog-footer">
        <el-button @click="rightDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="allotRights">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    return {
      // 角色数据列表
      roleList: [],
      rightDialogVisible: false,
      // 权限数据列表
      rightsList: [],
      defaultProps: {
        children: 'children',
        label: 'authName'
      },
      // 原角色所用的权限的id值数组
      defKeys: [],
      //   保存当前对话框对应的角色的id
      roleId: ''
    }
  },
  created() {
    // 调用函数获取角色数据
    this.getRolesList()
  },
  methods: {
    // 获取角色数据函数
    async getRolesList() {
      const { data: res } = await this.$http.get('roles')
      console.log(res)
      if (res.meta.status !== 200) {
        return this.$message.error('获取数据失败！')
      }
      this.roleList = res.data
    },
    // 删除权限函数
    async removeRightById(role, rightId) {
      // 消息弹框 返回promise对象
      const confirmResult = await this.$confirm(
        '此操作将永久删除该文件, 是否继续?',
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      ).catch(err => err)
      if (confirmResult !== 'confirm') {
        return this.$message.info('取消删除操作！')
      }
      //   发送请求
      const { data: res } = await this.$http.delete(
        `roles/${role.id}/rights/${rightId}`
      )
      if (res.meta.status !== 200) {
        return this.$message.error('删除失败！')
      }
      //   console.log(res)
      //   将数据赋值给当前权限列表
      role.children = res.data
      this.$message.success('删除成功！')
    },

    // 控制权限操作对话框
    async showRightDialog(role) {
      // 获取当前角色的id
      this.roleId = role.id
      const { data: res } = await this.$http.get('rights/tree')
      if (res.meta.status !== 200) {
        return this.$message.error('获取权限列表失败！')
      }
      this.rightsList = res.data

      this.getLeafKeys(role, this.defKeys)
      this.rightDialogVisible = true
    },
    // 通过递归数组获取id值
    getLeafKeys(node, arr) {
      // 若传入的数据对象没有children即第三级，将该对象的id值存到数组中
      if (!node.children) {
        return arr.push(node.id)
      }
      // 若有children属性，则通过forEach循环
      node.children.forEach(item => {
        this.getLeafKeys(item, arr)
      })
    },
    // 监听对话框关闭清除表单数据
    setRightDialogClosed() {
      this.defKeys = []
    },
    // 角色权限授权
    async allotRights() {
      const keys = [
        ...this.$refs.treeRef.getCheckedKeys(),
        ...this.$refs.treeRef.getHalfCheckedKeys()
      ]
      const idStr = keys.join(',')
      const { data: res } = await this.$http.post(
        `roles/${this.roleId}/rights`,
        { rids: idStr }
      )
      if (res.meta.status !== 200) {
        return this.$message.error('更新权限列表失败！')
      }
      this.$message.success('更新权限列表成功！')
      this.getRolesList()
      this.rightDialogVisible = false
    }
  }
}
</script>

<style lang='less' scoped>
.el-tag {
  margin: 7px;
}
.border-top {
  border-top: 1px solid #eee;
}
.border-bot {
  border-bottom: 1px solid #eee;
}
.vcenter {
  display: flex;
  align-items: center;
}
</style>
